<template>
    <div class="px-4 py-2 flex items-center" @click="amr.isPlaying() ? amr.stop() : amr.play()">
        <div class="icon mr-[10px]" :class="{ animate: data.isPlaying }"></div>
        <div class="time">{{durationDes}}</div>
    </div>
</template>
<script lang="ts">
let currentPlayingAmr: BenzAMRRecorder | null = null

</script>

<script setup lang="ts">
import BenzAMRRecorder from 'benz-amr-recorder';
import { onUnmounted, reactive, computed } from 'vue';
import * as api from '../api'

const props = defineProps<{
    msg: api.VoiceContent
}>()

let amr = new BenzAMRRecorder();
const data = reactive({
    isReady: false,
    isPlaying: false,
    duration: 0
})

const durationDes = computed(() => {
    if (data.duration <= 0) { return '⋯' }
    const duration = Math.ceil(data.duration)
    const min = Math.floor(duration / 60)
    const sec = duration % 60
    return `${min ? min + '′' : ''}${sec}″`
})

amr.initWithUrl(props.msg.content.content).then(() => {
    data.isReady = true
    data.duration = amr.getDuration()
})

amr.onPlay(() => {
    data.isPlaying = true
    currentPlayingAmr?.stop()
    currentPlayingAmr = amr
})
amr.onStop(() => {
    data.isPlaying = false
    currentPlayingAmr = null
})

onUnmounted(() => {
    amr.stop()
})

</script>

<style scoped>
.icon {
    display: inline-block;
    height: 20px;
    width: 20px;
    background-image: url(../assets/audio.svg);
    background-repeat: no-repeat;
    background-size: 60px 20px;
    background-position: right top;
}

.icon.animate {
    animation-name: voicePlay;
    animation-duration: 1.2s;
    animation-direction: normal;
    animation-iteration-count: infinite;
    animation-timing-function: steps(3, jump-none);
}

@keyframes voicePlay {
    0% {
        background-position: 0;
    }

    100% {
        background-position: 100%;
    }
}

.time {
    font-size: 14px;
    line-height: 22px;
}
</style>